//
//  PersonalViewController.m
//  MIDI
//
//  Created by 邵子凡 on 15/11/23.
//  Copyright © 2015年 QXSX. All rights reserved.
//

#import "PersonalViewController.h"
#import "AddHeadPhotoCell.h"
#import "AddNameCell.h"
#import "AddIDCell.h"
#import "AddllineCell.h"
#import "AddMailboxCell.h"
#import "AddCriterionCell.h"
#import "ChangeInforViewCtrl.h"
#import "UIViewController+Create.h"
#import "ChangePswViewCtrl.h"
#import "ChangePhoneNumViewCtrler.h"
#import "PerfectInfoController.h"
#import "UIViewController+NavItem.h"
#import "MBProgressHUD+YC.h"
#import "AppConfig.h"
#import "QXNetWorkTool.h"
#import "APIAdress.h"
#import "UserDataSingleton.h"
#import "SelfInfoModel.h"
#import "UIImageView+WebCache.h"
#import "CommFunc.h"
#import "ChangeInforViewCtrl.h"
#import "AddHeadImageCell.h"
#import "UIActionSheet+Blocks.h"

@interface PersonalViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate, QXNetWorkToolDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,UIActionSheetDelegate,AddHeadImageCellDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) AddNameCell *addNameCell;
@property (strong, nonatomic) AddIDCell *addIDCell;
@property (strong, nonatomic) AddMailboxCell *addMailboxCell;
//@property (strong, nonatomic) AddHeadPhotoCell *headPhotoCell;

@property (strong, nonatomic) AddHeadImageCell *headPhotoCell;

@property (assign , nonatomic) BOOL isNameRight;
@property (assign , nonatomic) BOOL isIDNumRight;
@property (assign , nonatomic) BOOL isEmailRight;
@property (strong , nonatomic) NSMutableDictionary *infoDic;
@property (strong , nonatomic) UIActionSheet *myActionSheet;

@end

@implementation PersonalViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.infoDic = [[NSMutableDictionary alloc]init];
    
    self.isNameRight = NO;
    self.isIDNumRight = NO;
    self.isEmailRight = NO;
}

- (void)settingNavigation{
    
    //设置导航栏标题
    self.navigationItem.title = @"个人信息";
    
    //设置导航栏标题字体颜色（字体大小也可以在这里设置）
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    //设置导航栏右边按钮
//    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(saveBtn:)];
//    rightBtn.tintColor = UIColorRGBA(19, 208, 202, 1);
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
                          
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [rightBtn setTitleColor:UIColorRGBA(19, 208, 202, 1) forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(saveBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self reqSelfInfo];
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //设置导航栏左边返回按钮
    [self configNavigationBackAction:^{
        
        [self.navigationController popViewControllerAnimated:YES];
        
        [[UserDataSingleton shareInstance] clearLocalHeadImage];
    }];
    
    //设置导航
    [self settingNavigation];
}

//请求个人数据
-(void)reqSelfInfo
{
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    QXNetWorkTool *tool = [[QXNetWorkTool alloc]init];
    
    tool.QXNetWorkDelegate = self;
    
    UserDataSingleton *userdata = [UserDataSingleton shareInstance];
    [tool GetDataFromServerWithPostMethodandInterfaceName:GetSelfInfoInterface andParameter:@[@{@"user_id":userdata.user_id}] tag:2];
}

#pragma mark  ----QXNetTool----------------
-(void)GetSuccessResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    
    if(tag == 1)
    {
        [UserDataSingleton shareInstance].isSelfInfoChange = YES;
        UserDataSingleton *userdata = [UserDataSingleton shareInstance];
        userdata.real_name = [self.infoDic objectForKey:@"real_name"];
        userdata.eamil = [self.infoDic objectForKey:@"eamil"];
        userdata.id_card = [self.infoDic objectForKey:@"id_card"];
        
        userdata.id_card = [userdata.id_card uppercaseString];
        
        [[UserDataSingleton shareInstance] clearLocalHeadImage];
    }
    else if (tag == 2)
    {
        SelfInfoModel * data = nil;
        for(NSDictionary * dic in Response)
        {
            data = [SelfInfoModel MyModelWithDict:dic];
            break;
        }
        if(data == nil)
            return;
        UserDataSingleton *userdata = [UserDataSingleton shareInstance];
        userdata.isGotSelfInfo = YES;
        userdata.midi_id = data.midi_id;
        userdata.sex = data.sex;
        userdata.eamil = data.eamil;
        userdata.people = data.people;
        userdata.nationality = data.nationality;
        userdata.id_card = [data.id_card uppercaseString];
        userdata.head_img = data.head_img;
        userdata.nickname = data.nickname;
        userdata.real_name = data.real_name;
        userdata.phone = data.phone;
        userdata.birthday = data.birthday;
        userdata.isSelfInfoChange = NO;
        [self.tableView reloadData];
    }
}

-(void)GetFailResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
}

-(void)GetSuccessMessage:(id)message andTag:(int)tag
{
    [MBProgressHUD showSuccess:(NSString *)message toView:self.view];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 9;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        
        return [CommFunc getMyselfHeadCellHeight];
    
    }else if (indexPath.row == 1){
        
        return 50;
    }else if (indexPath.row == 2){
        
        return 50;
    }else if (indexPath.row == 3){
        
        return 12;
    }else if (indexPath.row == 4){
        
        return 50;
    }else if (indexPath.row == 5){
        
        return 50;
    }else if (indexPath.row == 6){
        
        return 12;
    }else if (indexPath.row == 7){
        
        return 50;
    }else if (indexPath.row == 8){
        
        return 50;
    }
    
    return 1;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        
        self.headPhotoCell = [AddHeadImageCell cellWithTableView:tableView];
        
        [self.headPhotoCell hideArrow];
        
        self.headPhotoCell.delegete = self;
        
        return self.headPhotoCell;
        
    }else if (indexPath.row == 1){
        
        self.addNameCell = [AddNameCell cellWithTableView:tableView];
        
        self.addNameCell.nameTextField.tag = 1;
        
        self.addNameCell.nameTextField.delegate = self;
        
        UserDataSingleton * userdata = [UserDataSingleton shareInstance];
        if ([userdata.real_name isEqualToString:@""])
        {
            self.isNameRight = NO;
        }
        else
        {
            self.isNameRight = YES;
        }
        
        return self.addNameCell;
        
    }else if (indexPath.row == 2){
        
        self.addIDCell = [AddIDCell cellWithTableView:tableView];
        
        self.addIDCell.IDTextField.tag = 2;
        
        self.addIDCell.IDTextField.delegate = self;
        
        UserDataSingleton * userdata = [UserDataSingleton shareInstance];
        
        if ([CommFunc validateIDCardNumber:userdata.id_card])
        {
            self.isIDNumRight = YES;
        }
        else
        {
            self.isIDNumRight = NO;
        }
        
        return self.addIDCell;
        
    }else if (indexPath.row == 3){
        
        AddllineCell *cell = [AddllineCell cellWithTableView:tableView];
        
        return cell;
        
    }else if (indexPath.row == 4){
        
        self.addMailboxCell = [AddMailboxCell cellWithTableView:tableView];
        
        self.addMailboxCell.mailTextField.tag = 3;
        
        self.addMailboxCell.mailTextField.delegate = self;
        
        UserDataSingleton * userdata = [UserDataSingleton shareInstance];
        if ([CommFunc isValidateEmail:userdata.eamil])
        {
            self.isEmailRight = YES;
        }
        else
        {
            self.isEmailRight = NO;
        }
        
        return self.addMailboxCell;
        
    }else if (indexPath.row == 5){
        
        AddCriterionCell *cell = [AddCriterionCell cellWithTableView:tableView];
        
        cell.image.image = [UIImage imageNamed:@"ico_selfinfo_completeinfo1"];
        
        cell.label.text = @"完善信息";
        
        return cell;
        
    }else if (indexPath.row == 6){
        
        AddllineCell *cell = [AddllineCell cellWithTableView:tableView];
        
        return cell;
        
    }else if (indexPath.row == 7){
        
        AddCriterionCell *cell = [AddCriterionCell cellWithTableView:tableView];
        
        cell.image.image = [UIImage imageNamed:@"ico_selfinfo_changepsw"];
        
        cell.label.text = @"修改密码";
        
        cell.imageXConstraint.constant += 2;
        cell.labelXConstraint.constant += 1;
        
        return cell;
        
    }else if (indexPath.row == 8){
        
        AddCriterionCell *cell = [AddCriterionCell cellWithTableView:tableView];
        
        cell.image.image = [UIImage imageNamed:@"ico_selfinfo_changephonenum"];
        
        cell.label.text = @"修改手机号码";
        
        cell.imageXConstraint.constant += 5;
        cell.labelXConstraint.constant += 4;
        
        return cell;
    }
    
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    return cell;
}

//cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row == 5) {
        
        [self.navigationController pushViewController:[PerfectInfoController create] animated:YES];
        
    }else if (indexPath.row == 7){
        
        [self.navigationController pushViewController:[ChangePswViewCtrl create] animated:YES];
        
    }else if (indexPath.row == 8){
        
        [self.navigationController pushViewController:[ChangePhoneNumViewCtrler create] animated:YES];
        
    }
}
//更改头像

- (void)uploadHeadImageBtn
{
    self.myActionSheet = [[UIActionSheet alloc]
                          initWithTitle:nil
                          delegate:self
                          cancelButtonTitle:@"取消"
                          destructiveButtonTitle:nil
                          otherButtonTitles:@"打开照相机", @"从手机相册获取", nil];
    
    [self.myActionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == self.myActionSheet.cancelButtonIndex) {
    }
    
    switch (buttonIndex) {
        case 0:
            [self takePhoto];
            break;
            
        case 1:
            [self LocalPhoto];
            break;
    }
}

//打开相机
- (void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:^{
            NSLog(@"OK");
        }];
    }
    else {
        NSLog(@"模拟其中无法打开照相机，请在真机中使用");
    }
}

//读取相册
- (void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:^{
        
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image;
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        
        image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        
        [self.headPhotoCell.headImage setImage:image];
        
        //将图片保存的本地
        [[UserDataSingleton shareInstance] setLocalHeadImageData:image];
        
        self.headPhotoCell.headImage.contentMode = UIViewContentModeScaleAspectFill;
        
        [picker dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark --- UITextFieldDelegate

//当textField 编辑结束的时候
- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    switch (textField.tag) {
        case 1:
        {
          if (textField.text == nil || [textField.text isEqualToString:@""]) {
                
                [MBProgressHUD showError:@"请输入你的姓名"];
                
                self.isNameRight = NO;
                
            }
            self.isNameRight = YES;
            
            break;
        }
        case 2:
        {
            textField.text = [textField.text uppercaseString];
            
            BOOL isRightIDNum = [CommFunc validateIDCardNumber:textField.text];
            if(!isRightIDNum)
            {
                [MBProgressHUD showError:@"请输入正确的身份证号"];
                self.isIDNumRight = NO;
            }
            
            self.isIDNumRight = YES;
            
            break;
        }
            
        case 3:
        {
            BOOL isRightEmail = [CommFunc isValidateEmail:textField.text];
            if(!isRightEmail)
            {
                self.isEmailRight = NO;
                [MBProgressHUD showError:@"请输入正确的email"];
            }
           
            self.isEmailRight = YES;
            
            break;
        }
        default:
            break;
    }
}

//导航栏右边按钮的事件实现
- (void)saveBtn:(id)sender{
    
    if (self.isNameRight == NO) {
        
        [MBProgressHUD showError:@"请输入姓名"];
        return;
        
    }else if (self.isIDNumRight == NO) {
        
        [MBProgressHUD showError:@"请输入正确的身份证号"];
        return;
        
    }else if (self.isEmailRight == NO) {
        
        [MBProgressHUD showError:@"请输入正确的email"];
        return;
    }
    
    NSMutableDictionary * dic = self.infoDic;
    [dic removeAllObjects];
    UserDataSingleton *userdata = [UserDataSingleton shareInstance];
    [dic setValue:self.addNameCell.nameTextField.text forKey:@"real_name"];
    [dic setValue:userdata.user_id forKey:@"user_id"];
    [dic setValue:userdata.nickname forKey:@"nickname"];
    [dic setValue:self.addMailboxCell.mailTextField.text forKey:@"eamil"];
    [dic setValue:[self.addIDCell.IDTextField.text uppercaseString] forKey:@"id_card"];
    
    [dic setValue:userdata.province forKey:@"province"];
    [dic setValue:userdata.curCityId forKey:@"city"];
    [dic setValue:userdata.phone forKey:@"phone"];
    [dic setValue:userdata.nationality forKey:@"nationality"];
    [dic setValue:userdata.sex forKey:@"sex"];
    [dic setValue:userdata.birthday forKey:@"birthday"];
    [dic setValue:userdata.people forKey:@"people"];
    
    if (self.headPhotoCell)
    {
        UIImage *image = self.headPhotoCell.headImage.image;
        
        if (image)
        {
            [dic setValue:[CommFunc getImageBase64String:image] forKey:@"head_img"];
        }
        else
        {
            [dic setValue:@"" forKey:@"head_img"];
        }
    }
    else
    {
        [dic setValue:@"" forKey:@"head_img"];
    }
    
    
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    QXNetWorkTool *tool = [[QXNetWorkTool alloc]init];
    
    tool.QXNetWorkDelegate = self;
    
    [tool GetDataFromServerWithPostMethodandInterfaceName:FillDetailInterface andParameter:@[dic] tag:1];
}

@end









